package com.foftact.etfweekly;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ETF周线数据控制器
 * 提供ETF周线数据相关的RESTful API接口
 */
@Controller
@RequestMapping("/api/etfweekly")
public class ETFWeeklyController {

    private static final Logger logger = LoggerFactory.getLogger(ETFWeeklyController.class);

    @Autowired
    private ETFWeeklyService etfWeeklyService;

    /**
     * 抓取并保存ETF周线数据
     * @param code 板块/ETF代码
     * @return 操作结果
     */
    @PostMapping("/fetch")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> fetchAndSaveETFWeeklyData(@RequestParam String code) {
        logger.info("接收抓取ETF周线数据请求，代码: {}", code);
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean success = etfWeeklyService.fetchAndSaveETFWeeklyData(code);
            if (success) {
                result.put("status", "success");
                result.put("message", "ETF周线数据抓取成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("status", "error");
                result.put("message", "ETF周线数据抓取失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            logger.error("抓取ETF周线数据异常，代码: {}", code, e);
            result.put("status", "error");
            result.put("message", "抓取过程中发生异常: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

//    /**
//     * 写入或更新ETF周线数据
//     * 根据需求：近10条数据已存在则不写入，近10条不存在或不完整则写入更新近1年数据，近3条数据强制更新
//     * @param code 板块/ETF代码
//     * @return 操作结果
//     */
//    @PostMapping("/writeOrUpdate")
//    @ResponseBody
//    public ResponseEntity<Map<String, Object>> writeOrUpdateETFWeeklyData(@RequestParam String code) {
//        logger.info("接收写入或更新ETF周线数据请求，代码: {}", code);
//        Map<String, Object> result = new HashMap<>();
//
//        try {
//            boolean success = etfWeeklyService.writeOrUpdateETFWeeklyData(code);
//            if (success) {
//                result.put("status", "success");
//                result.put("message", "ETF周线数据写入更新成功");
//                return ResponseEntity.ok(result);
//            } else {
//                result.put("status", "error");
//                result.put("message", "ETF周线数据写入更新失败");
//                return ResponseEntity.badRequest().body(result);
//            }
//        } catch (Exception e) {
//            logger.error("写入更新ETF周线数据异常，代码: {}", code, e);
//            result.put("status", "error");
//            result.put("message", "写入更新过程中发生异常: " + e.getMessage());
//            return ResponseEntity.badRequest().body(result);
//        }
//    }

    /**
     * 根据板块/ETF代码和日期范围获取ETF周线数据
     * @param code 板块/ETF代码
     * @param startDate 开始日期（格式：YYYY-MM-DD）
     * @param endDate 结束日期（格式：YYYY-MM-DD）
     * @return ETF周线数据列表
     */
    @GetMapping("/byRange")
    @ResponseBody
    public ResponseEntity<ETFWeeklyResponseDTO> getETFWeeklyByCodeAndDateRange(
            @RequestParam String code,
            @RequestParam String startDate,
            @RequestParam String endDate) {
        
        logger.info("接收查询ETF周线数据请求，代码: {}, 开始日期: {}, 结束日期: {}", 
                code, startDate, endDate);
        
        ETFWeeklyResponseDTO response = new ETFWeeklyResponseDTO();
        
        try {
            List<ETFWeekly> dataList = etfWeeklyService.getETFWeeklyByCodeAndDateRange(code, startDate, endDate);
            response.setDatas(dataList);
            response.setAllRecords(dataList.size());
            response.setStatus("success");
            response.setMsg("查询成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("查询ETF周线数据异常", e);
            response.setStatus("error");
            response.setMsg("查询失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取所有ETF周线数据
     * @return ETF周线数据列表
     */
    @GetMapping("/all")
    @ResponseBody
    public ResponseEntity<ETFWeeklyResponseDTO> getAllETFWeekly() {
        logger.info("接收查询所有ETF周线数据请求");
        
        ETFWeeklyResponseDTO response = new ETFWeeklyResponseDTO();
        
        try {
            List<ETFWeekly> dataList = etfWeeklyService.getAllETFWeekly();
            response.setDatas(dataList);
            response.setAllRecords(dataList.size());
            response.setStatus("success");
            response.setMsg("查询成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("查询所有ETF周线数据异常", e);
            response.setStatus("error");
            response.setMsg("查询失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取指定板块/ETF的最近N条ETF周线数据
     * @param code 板块/ETF代码
     * @param limit 记录条数
     * @return ETF周线数据列表
     */
    @GetMapping("/recent")
    @ResponseBody
    public ResponseEntity<ETFWeeklyResponseDTO> getRecentETFWeeklyByCode(
            @RequestParam String code,
            @RequestParam(required = false, defaultValue = "10") Integer limit) {
        
        logger.info("接收查询最近ETF周线数据请求，代码: {}, 记录条数: {}", code, limit);
        
        ETFWeeklyResponseDTO response = new ETFWeeklyResponseDTO();
        
        try {
            List<ETFWeekly> dataList = etfWeeklyService.getRecentETFWeeklyByCode(code, limit);
            response.setDatas(dataList);
            response.setAllRecords(dataList.size());
            response.setStatus("success");
            response.setMsg("查询成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("查询最近ETF周线数据异常", e);
            response.setStatus("error");
            response.setMsg("查询失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 保存单个ETF周线数据
     * @param etfWeekly ETF周线数据
     * @return 操作结果
     */
    @PostMapping("/save")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> saveETFWeekly(@RequestBody ETFWeekly etfWeekly) {
        logger.info("接收保存ETF周线数据请求");
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean success = etfWeeklyService.saveETFWeekly(etfWeekly);
            if (success) {
                result.put("status", "success");
                result.put("message", "ETF周线数据保存成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("status", "error");
                result.put("message", "ETF周线数据保存失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            logger.error("保存ETF周线数据异常", e);
            result.put("status", "error");
            result.put("message", "保存过程中发生异常: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 更新ETF周线数据
     * @param etfWeekly ETF周线数据
     * @return 操作结果
     */
    @PutMapping("/update")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> updateETFWeekly(@RequestBody ETFWeekly etfWeekly) {
        logger.info("接收更新ETF周线数据请求");
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean success = etfWeeklyService.updateETFWeekly(etfWeekly);
            if (success) {
                result.put("status", "success");
                result.put("message", "ETF周线数据更新成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("status", "error");
                result.put("message", "ETF周线数据更新失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            logger.error("更新ETF周线数据异常", e);
            result.put("status", "error");
            result.put("message", "更新过程中发生异常: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 删除ETF周线数据
     * @param id 主键ID
     * @return 操作结果
     */
    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> deleteETFWeekly(@PathVariable Long id) {
        logger.info("接收删除ETF周线数据请求，ID: {}", id);
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean success = etfWeeklyService.deleteETFWeekly(id);
            if (success) {
                result.put("status", "success");
                result.put("message", "ETF周线数据删除成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("status", "error");
                result.put("message", "ETF周线数据删除失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            logger.error("删除ETF周线数据异常，ID: {}", id, e);
            result.put("status", "error");
            result.put("message", "删除过程中发生异常: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 根据板块/ETF代码和日期删除ETF周线数据
     * @param code 板块/ETF代码
     * @param weekDate 周日期（格式：YYYY-MM-DD）
     * @return 操作结果
     */
    @DeleteMapping("/deleteByCodeAndDate")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> deleteETFWeeklyByCodeAndDate(
            @RequestParam String code,
            @RequestParam String weekDate) {
        
        logger.info("接收删除ETF周线数据请求，代码: {}, 周日期: {}", code, weekDate);
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean success = etfWeeklyService.deleteETFWeeklyByCodeAndDate(code, weekDate);
            if (success) {
                result.put("status", "success");
                result.put("message", "ETF周线数据删除成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("status", "error");
                result.put("message", "ETF周线数据删除失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            logger.error("删除ETF周线数据异常", e);
            result.put("status", "error");
            result.put("message", "删除过程中发生异常: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 清空ETF周线数据表
     * @return 操作结果
     */
    @DeleteMapping("/truncate")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> truncateETFWeeklyTable() {
        logger.info("接收清空ETF周线数据表请求");
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean success = etfWeeklyService.truncateETFWeeklyTable();
            if (success) {
                result.put("status", "success");
                result.put("message", "ETF周线数据表清空成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("status", "error");
                result.put("message", "ETF周线数据表清空失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            logger.error("清空ETF周线数据表异常", e);
            result.put("status", "error");
            result.put("message", "清空过程中发生异常: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 跳转到ETF周线数据页面
     * @return ETF周线数据页面
     */
    @GetMapping("/page")
    public String etfWeeklyPage() {
        return "etf2/etfWeekly";
    }
}